<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="来往款类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择来往款类型"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="item in wlktsTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="责任科室" prop="dutyDept">
        <el-select
          v-model="queryParams.dutyDept"
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="searchDeptByName"
          :loading="searchLoading"
          style="width: 200px"
        >
          <el-option
            v-for="item in deptOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="到期时间" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          style="width: 240px"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:wlkts:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
             <el-button
                type="warning"
                plain
                icon="Download"
                @click="handleExport"
                v-hasPermi="['business:wlkts:export']"
             >导出</el-button>
          </el-col> -->
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="wlktsList" border>
      <el-table-column
        label="提醒类型"
        align="center"
        width="150"
        :fixed="true"
      >
        <template #default="scope">
          <el-tag
            v-if="
              scope.row.completeTime === null &&
              new Date(scope.row.endTime).getTime() >=
                new Date().getTime() + 30 * 24 * 60 * 60 * 1000 &&
              new Date(scope.row.endTime).getTime() <=
                new Date().getTime() + 90 * 24 * 60 * 60 * 1000
            "
            type="info"
            >三个月内到期</el-tag
          >
          <el-tag
            v-if="
              scope.row.completeTime === null &&
              new Date(scope.row.endTime).getTime() <=
                new Date().getTime() + 30 * 24 * 60 * 60 * 1000 &&
              new Date(scope.row.endTime).getTime() > new Date().getTime()
            "
            type="warning"
            >一个月内到期</el-tag
          >
          <el-tag
            v-else-if="
              scope.row.completeTime === null &&
              scope.row.endTime != null &&
              new Date(scope.row.endTime).getTime() < new Date().getTime()
            "
            type="danger"
            >逾期提醒</el-tag
          >
          <el-tag
            v-else-if="
              scope.row.completeTime === null &&
              new Date(scope.row.endTime).getTime() >
                new Date().getTime() + 90 * 24 * 60 * 60 * 1000
            "
            type="primary"
            >三个月以上到期</el-tag
          >
          <el-tag v-else-if="scope.row.completeTime != null" type="success"
            >已完成</el-tag
          >
          <span v-else-if="scope.row.endTime === null"> </span>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="title" width="150" />
      <el-table-column
        label="类型"
        align="center"
        :show-overflow-tooltip="true"
        width="120"
      >
        <template #default="scope">
          <span>{{ getWlktsTypeLabel(scope.row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="金额（元）"
        align="center"
        prop="amount"
        :show-overflow-tooltip="true"
        width="120"
      />
      <el-table-column
        label="对方公司（个人）"
        align="center"
        prop="partyB"
        width="150"
      />
      <el-table-column
        label="所属项目名称"
        align="center"
        prop="projectName"
        width="150"
      />
      <el-table-column
        label="项目周期"
        align="center"
        prop="projectCycle"
        width="200"
      />
      <el-table-column
        label="责任科室"
        align="center"
        prop="dutyDeptName"
        width="100"
      />
      <el-table-column
        label="经办人"
        align="center"
        prop="operator"
        width="100"
      />
      <el-table-column
        label="联系方式"
        align="center"
        prop="phone"
        width="100"
      />
      <el-table-column
        label="到期日期"
        align="center"
        prop="endTime"
        width="100"
        :formatter="formatDate"
      />
      <el-table-column
        label="完成日期"
        align="center"
        prop="completeTime"
        width="100"
        :formatter="formatDate"
      />
      <el-table-column label="备注" align="center" prop="remark" width="200" />
      <el-table-column
        label="操作"
        align="left"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            style="margin-left: 12px"
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:wlkts:edit']"
            >编辑</el-button
          >
          <el-button
            link
            type="success"
            icon="view"
            @click="handleView(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getWlkList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form
        class="dialog-content"
        ref="wlktsRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <div>
          <el-form-item label="名称" prop="title">
            <el-input
              v-model="form.title"
              placeholder="请输入名称"
              clearable
              :disabled="view"
            ></el-input>
          </el-form-item>
        </div>
        <div class="row">
          <el-form-item label="类型" prop="type" style="flex: 1">
            <el-select
              v-model="form.type"
              placeholder="请选择类型"
              clearable
              :disabled="view"
            >
              <el-option
                v-for="item in wlktsTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="金额(元)" prop="amount" style="flex: 1">
            <el-input
              type="number"
              v-model="form.amount"
              placeholder="请输入金额"
              clearable
              :disabled="view"
            ></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="对方公司" prop="partyB">
            <el-input
              v-model="form.partyB"
              placeholder="请输入对方公司或个人"
              clearable
              :disabled="view"
            ></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="所属项目名称" prop="projectName">
            <el-input
              v-model="form.projectName"
              placeholder="请输入所属项目名称"
              clearable
              :disabled="view"
            ></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="项目周期" prop="projectCycle">
            <el-date-picker
              v-model="dateRange"
              type="monthrange"
              range-separator="至"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              value-format="YYYY-MM"
              :disabled="view"
            >
            </el-date-picker>
          </el-form-item>
        </div>
        <div class="row">
          <el-form-item label="责任科室" style="flex: 1">
            <el-select
              v-model="form.dutyDept"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="searchDeptByName"
              :loading="searchLoading"
              @change="selectDept"
              :disabled="view"
            >
              <el-option
                v-for="item in deptOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="经办人" prop="operator" style="flex: 1">
            <el-input
              v-model="form.operator"
              placeholder="请输入经办人"
              clearable
              :disabled="view"
            ></el-input>
          </el-form-item>
        </div>
        <div class="row">
          <el-form-item label="联系方式" prop="phone" style="flex: 1">
            <el-input
              v-model="form.phone"
              placeholder="请输入联系方式"
              clearable
              :disabled="view"
            ></el-input>
          </el-form-item>
          <el-form-item label="到期日期" prop="endTime" style="flex: 1">
            <el-date-picker
              v-model="form.endTime"
              type="date"
              placeholder="选择日期"
              clearable
              value-format="YYYY-MM-DD"
              :disabled="view"
            ></el-date-picker>
          </el-form-item>
        </div>
        <div class="row">
          <el-form-item label="完成日期" prop="completeTime" style="flex: 1">
            <el-date-picker
              v-model="form.completeTime"
              type="date"
              placeholder="选择日期"
              clearable
              value-format="YYYY-MM-DD"
              :disabled="view"
            ></el-date-picker>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              v-model="form.remark"
              placeholder="请输入备注"
              :rows="5"
              clearable
              :disabled="view"
            ></el-input>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!view" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="wlkts">
import { listWlkts, addWlkts, editWlkts, delWlkts } from "@/api/business/wlkts";
import { listData } from "@/api/system/dict/data";
import { listDept } from "@/api/system/dept";

const { proxy } = getCurrentInstance();

const wlktsList = ref([]);
const open = ref(false);
const view = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const deptRef = ref(null);
const searchLoading = ref(false);
const deptOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: undefined,
    dutyDept: undefined,
    dateRange: [],
    beginTime: undefined,
    endTime: undefined,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

const wlktsTypes = ref([]);
/** 获取往来款类型字典值 */
function getWlktsType() {
  listData({
    dictType: "wlk_type",
  }).then((response) => {
    const types = response.rows;
    wlktsTypes.value = types.map((item) => {
      return {
        label: item.dictLabel,
        value: item.dictValue,
      };
    });
  });
}

/** 获取往来款类型标签 */
function getWlktsTypeLabel(value) {
  const type = wlktsTypes.value.find((item) => item.value === value);
  return type ? type.label : "";
}

/** 查询部门信息 */
function searchDeptByName(query) {
  if (query !== "") {
    searchLoading.value = true;
    listDept({
      deptName: query,
    }).then((response) => {
      deptOptions.value = response.data.map((item) => {
        return {
          label: item.deptName,
          value: item.deptId,
        };
      });
      searchLoading.value = false;
    });
  } else {
    searchLoading.value = true;
    listDept({
      parentId: 100,
    }).then((response) => {
      deptOptions.value = response.data.map((item) => {
        return {
          label: item.deptName,
          value: item.deptId,
        };
      });
      searchLoading.value = false;
    });
  }
}

/** 选择部门 */
function selectDept(value) {
  // form.value.dutyDept = value;
  form.value.dutyDeptName = deptOptions.value.find(
    (item) => item.value === value
  ).label;
}

/** 格式化日期 */
function formatDate(row, column) {
  return row[column.property]
    ? JSON.stringify(row[column.property]).slice(1, 11)
    : "";
}

/** 查询往来款列表 */
function getWlkList() {
  listWlkts(queryParams.value).then((response) => {
    wlktsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  queryParams.value.beginTime = queryParams.value.dateRange[0];
  queryParams.value.endTime = queryParams.value.dateRange[1];
  getWlkList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const roleIds = row.roleId || ids.value;
  proxy.$modal
    .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?')
    .then(function () {
      return delRole(roleIds);
    })
    .then(() => {
      getWlkList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/role/export",
    {
      ...queryParams.value,
    },
    `role_${new Date().getTime()}.xlsx`
  );
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    id: undefined,
    title: undefined,
    type: undefined,
    amount: undefined,
    partyB: "",
    projectName: "",
    projectCycle: "",
    dutyDept: undefined,
    dutyDeptName: "",
    operator: "",
    phone: "",
    endTime: undefined,
    status: "0",
    completeTime: undefined,
    remark: undefined,
  };
  dateRange.value = [];
  proxy.resetForm("wlktsRef");
}
/** 添加往来款记录 */
function handleAdd() {
  reset();
  open.value = true;
  view.value = false;
  title.value = "添加往来款记录";
}
/** 修改往来款记录 */
function handleUpdate(row) {
  reset();
  form.value = { ...row };
  dateRange.value = row.projectCycle?.split("至");
  open.value = true;
  view.value = false;
  title.value = "修改往来款记录";
}
/** 查看往来款记录 */
function handleView(row) {
  reset();
  form.value = { ...row };
  dateRange.value = row.projectCycle?.split("至");
  view.value = true;
  open.value = true;
  title.value = "查看往来款记录";
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["wlktsRef"].validate((valid) => {
    if (valid) {
      form.value.projectCycle = dateRange.value?.join("至");
      if (form.value.id != undefined) {
        editWlkts(form.value).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getWlkList();
        });
      } else {
        addWlkts(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getWlkList();
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

getWlkList();
getWlktsType();
</script>

<style scoped lang="less">
.dialog-content {
  width: 90%;
  .row {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
}
</style>
